package com.liziguo.lzgfp.system.handler;

import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * @Author: Liziguo
 * @Date: 2021/12/24 19:43
 */
public class ForWardHandler extends ChannelInboundHandlerAdapter {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    private final Channel channel;

    public ForWardHandler(Channel channel) {
        this.channel = channel;
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        TemporaryStorageHandler storage = ctx.channel().pipeline().get(TemporaryStorageHandler.class);
        if (storage == null) {
            logger.warn("未添加临时存储处理器,这可能导致数据丢失");
        } else {
            ctx.channel().pipeline().remove(storage);
            ByteBuf buf = storage.getByteBuf();
            channel.writeAndFlush(buf);
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//        logger.debug(((ByteBuf) (msg)).toString(StandardCharsets.UTF_8));
        channel.writeAndFlush(msg);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        logger.info("转发通道关闭{} {}", ctx.channel().remoteAddress(), channel.remoteAddress());
        channel.close();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error(cause.getMessage());
        cause.printStackTrace();
        channel.close();
        ctx.close();
    }
}
